package com.jh.jingfei.repositories;

import com.jh.jingfei.models.Account;
import com.strongloop.android.loopback.AccessToken;
import com.strongloop.android.loopback.AccessTokenRepository;
import com.strongloop.android.remoting.JsonUtil;
import com.strongloop.android.remoting.adapters.Adapter;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * @author lxb
 *         <p>
 *         Created by lion on 2017/12/7.
 */

public class AccountRepository extends com.strongloop.android.loopback.UserRepository<Account> {

    private AccessTokenRepository mAccessTokenRepository;

    public AccountRepository() {
        super("Account", Account.class);
    }

    /**
     * Login a user given an email and password.
     * Creates a {@link AccessToken} and {@code U} user models if successful.
     *
     * @param username - user email
     * @param password - user password
     * @param callback - success/error callback
     */
    public void loginUserWithUsername(String username, String password, final LoginCallback<Account> callback) {
        
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("username", username);
        params.put("password", password);

        invokeStaticMethod("login", params, new Adapter.JsonObjectCallback() {

            @Override
            public void onError(Throwable t) {
                callback.onError(t);
            }

            @Override
            public void onSuccess(JSONObject response) {
                if (mAccessTokenRepository == null) {
                    mAccessTokenRepository = getRestAdapter().createRepository(AccessTokenRepository.class);
                }
                AccessToken token = mAccessTokenRepository.createObject(JsonUtil.fromJson(response));

                getRestAdapter().setAccessToken(token.getId().toString());

                JSONObject userJson = response.optJSONObject("user");
                Account user = userJson != null
                        ? createObject(JsonUtil.fromJson(userJson))
                        : null;

                setCurrentUserId(token.getUserId());
                callback.onSuccess(token, user);
            }
        });
    }
}
